package cn.ddm.hrm.handler;

import cn.ddm.hrm.util.AjaxResult;
import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component //认证实现失败处理
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("text/html;charset=UTF-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());//401
        PrintWriter writer = response.getWriter();
        AjaxResult me = AjaxResult.me().setSuccess(false).setMessage("认证失败！");
        writer.write(JSON.toJSONString(me));
        writer.flush();
        writer.close();
    }
}
